o
Arrays Timm Mar10 Sandbox Revised

Printing an Array

Problem
=======

Printing an array is a very common task. How to do it succinctly?

Solution
========

Synopsis
--------

  o(array [,prefix,control])

Options:

- If _prefix_ is given,  print it before each item.
- If _control_ is a positive integer, then print from 1 to _control_.
- If _control_ is zero, the print in any order.
- Else, if the size of the _array_ is stored at location _array[0]_ then print from one to size.
- Else, if _control_ is a string, use it as  an  argument to a UNIX sort command (otherwise, just sort numerically by the _array_ values).

Code 
----

Print one array
+++++++++++++++

o
___

 function o(a, str,control,   i,com) {
     str = str ? str : "array"
     if (control ~ /^[0-9]/)  {
         if (control==0)
             o1(a,str)
         else
             for(i=1;i<=control;i++)
                 print oprim(str,i,a)
     } else
         if (0 in a) # sometimes i store array size in a[0]
	     o(a,str,a[0])         
         else {
             com = control ? control : " -n -k 2" 
             com = "sort " com  " #" rand(); # com is unique
             for(i in a)
                 print oprim(str,i,a) | com;
             close(com); }
 }
				      
The _oprim_ function prints one item, after the prefix string.

 function oprim(prefix,i,a,  j) {
     j=i
     gsub(SUBSEP,",",j) 
     return prefix "[ " j " ]\t=\t [ " a[i] " ]"
 }

Simpler
+++++++
 
oo
__
                                                                                  
When "_o_" is too complicated, use "_oo_".

 function oo(a,prefix, i) {
     for(i in a)
         print oprim(prefix,i,a)
 }

Many prints
+++++++++++

Sometimes, you want to print many arrays; e.g.

  os("Names",names,"Addresses",addresses,"Jobs",jobs)

os
__

Printing many items using the "_o_".

 function os(a1,pre1,a2,pre2,a3,pre3,a4,pre4,a5,pre5) {
     if(pre1) o(a1,pre1);
     if(pre2) o(a2,pre2);
     if(pre3) o(a3,pre3);
     if(pre4) o(a4,pre4);
     if(pre5) o(a5,pre5)
 }

oos
___

Print many items using the simpler list print.

  oos("Names",names,"Addresses",addresses,"Jobs",jobs)
 
 function oos(a1,pre1,a2,pre2,a3,pre3,a4,pre4,a5,pre5) {
     if(pre1) oo(a1,pre1);
     if(pre2) oo(a2,pre2);
     if(pre3) oo(a3,pre3);
     if(pre4) oo(a4,pre4);
     if(pre5) oo(a5,pre5)
 }

Author
======

Tim Menzies

